package com.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.baselearn.app.R;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

/**
 * Created by tukela on 2015/8/7.
 */
public class UpdateUtil  {


    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 检查更新 */
    private static final int XMLFINISH = 3;
    /* 检查是否有新版本 */
    private static final int CHECKVERSION = 4;
    private  String packageNmae;
    /* 保存解析的XML信息 */
    HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;
    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;

    private int serviceCode;
    private int versionCode;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                // 正在下载
                case XMLFINISH:
                    doCheckUpdate();
                    break;
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };

    public UpdateUtil(Context mContext,String  packageNmae){
        this.packageNmae=packageNmae;
        this. mContext=mContext;
    }
    public UpdateUtil(Context mContext){
        this. mContext=mContext;
    }

    /**
     * 检测软件更新
     */
    public void doCheckUpdate() {
        if (isUpdate()) {
            // 显示提示对话框
            showNoticeDialog();
        } else {
            Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_LONG).show();
        }
    }

    /* 获取服务器信息并解析*/
    public void faormatXML(String urlPath){
        if (null==urlPath||urlPath.equals(""))
        {
            return;
        }
        new Thread(){
            public void run() {
                try {
                    String path = "http://121.199.73.55:8080/mweb/update/version.xml";
                    URL url = new URL(urlPath);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setReadTimeout(5*1000);
                    conn.setRequestMethod("GET");
                    InputStream inStream = conn.getInputStream();
                    ParseXmlService service = new ParseXmlService();
                    mHashMap = service.parseXml(inStream);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

        }.start();

    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    public boolean isUpdate() {
        // 获取当前软件版本
        versionCode = getLocalVersionCode(mContext);
        // 把version.xml放到网络上，然后获取文件信息
        // InputStream inStream =
        // ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");
        // 解析XML文件。 由于XML文件比较小，因此使用DOM方式进行解析

        if (null != mHashMap) {
            serviceCode = Integer.valueOf(mHashMap.get("version"));
            // 版本判断
            if (serviceCode > versionCode) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前软件版本号
     *
     * @param context
     * @return
     */
    public int getLocalVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
//			versionCode = context.getPackageManager().getPackageInfo(
//					"com.example.hicashmobile", 0).versionCode;

            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageNmae, 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        new AlertDialog.Builder(mContext)
                .setTitle(R.string.soft_update_title)
                .setMessage(R.string.soft_update_info)
                .setPositiveButton(R.string.soft_update_updatebtn,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                // 显示下载对话框
                                showDownloadDialog();
                            }
                        })
                .setNegativeButton(R.string.soft_update_later,null)
                .show();

    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 给下载对话框增加进度条
//        final LayoutInflater inflater = LayoutInflater.from(mContext);
//        View v = inflater.inflate(R.layout.softupdate_progress, null);
//        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        ProgressBar mProgress=new ProgressBar(mContext);
        // 构造软件下载对话框
        new AlertDialog.Builder(mContext)
                .setTitle(R.string.soft_updating)
                .setView( mProgress)
                .setNegativeButton(R.string.soft_update_cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                // 设置取消状态
                                cancelUpdate = true;
                            }
                        })
                .show();
        // 现在文件
        new downloadApkThread().start();
    }



    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory()
                            + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(mHashMap.get("url"));
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, mHashMap.get("name"));
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    };



    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, mHashMap.get("name"));
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent();
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setAction(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }


    class ParseXmlService
    {
        public HashMap<String, String> parseXml(InputStream inStream) throws Exception
        {
            HashMap<String, String> hashMap = new HashMap<String, String>();

            // 实例化一个文档构建器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 通过文档构建器工厂获取一个文档构建器
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 通过文档通过文档构建器构建一个文档实例
            Document document = builder.parse(inStream);
            //获取XML文件根节点
            Element root = document.getDocumentElement();
            //获得所有子节点
            NodeList childNodes = root.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++)
            {
                //遍历子节点
                Node childNode = (Node) childNodes.item(j);
                if (childNode.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element childElement = (Element) childNode;
                    //版本号
                    if ("version".equals(childElement.getNodeName()))
                    {
                        hashMap.put("version",childElement.getFirstChild().getNodeValue());
                    }
                    //软件名称
                    else if (("name".equals(childElement.getNodeName())))
                    {
                        hashMap.put("name",childElement.getFirstChild().getNodeValue());
                    }
                    //下载地址
                    else if (("url".equals(childElement.getNodeName())))
                    {
                        hashMap.put("url",childElement.getFirstChild().getNodeValue());
                    }
                }
            }
            return hashMap;
        }
    }
}
